const express = require('express');
const router = express.Router();
const Application = require('../models/Application');
const { authenticateToken } = require('../middleware/auth');
const { 
  validateApplicationCreation, 
  validateApplicationProcess, 
  validateId, 
  validatePagination 
} = require('../middleware/validation');

// 创建申请
router.post('/', authenticateToken, validateApplicationCreation, async (req, res) => {
  try {
    const applicationData = {
      ...req.body,
      applicant_id: req.user.id
    };
    
    const application = await Application.create(applicationData);
    
    res.status(201).json({
      success: true,
      message: '申请提交成功',
      data: application
    });
  } catch (error) {
    console.error('创建申请错误:', error);
    
    if (error.message.includes('预约') || error.message.includes('申请') || error.message.includes('参与')) {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '申请提交失败'
    });
  }
});

// 获取我的申请列表
router.get('/my', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    const result = await Application.getUserApplications(req.user.id, page, limit);
    
    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取我的申请列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取申请列表失败'
    });
  }
});

// 获取预约的申请列表（仅预约创建者可查看）
router.get('/appointment/:appointmentId', authenticateToken, validateId, validatePagination, async (req, res) => {
  try {
    const appointmentId = req.params.appointmentId;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    const result = await Application.getAppointmentApplications(appointmentId, page, limit);
    
    res.json({
      success: true,
      data: result.data,
      pagination: result.pagination
    });
  } catch (error) {
    console.error('获取预约申请列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取申请列表失败'
    });
  }
});

// 处理申请（通过或拒绝）
router.put('/:id/process', authenticateToken, validateId, validateApplicationProcess, async (req, res) => {
  try {
    const applicationId = req.params.id;
    const { status, admin_notes } = req.body;
    
    const processedApplication = await Application.process(
      applicationId, 
      status, 
      req.user.id, 
      admin_notes
    );
    
    res.json({
      success: true,
      message: status === 'approved' ? '申请已通过' : '申请已拒绝',
      data: processedApplication
    });
  } catch (error) {
    console.error('处理申请错误:', error);
    
    if (error.message.includes('申请') || error.message.includes('预约') || error.message.includes('权限')) {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '处理申请失败'
    });
  }
});

// 取消申请
router.put('/:id/cancel', authenticateToken, validateId, async (req, res) => {
  try {
    const applicationId = req.params.id;
    
    const cancelledApplication = await Application.cancel(applicationId, req.user.id);
    
    res.json({
      success: true,
      message: '申请已取消',
      data: cancelledApplication
    });
  } catch (error) {
    console.error('取消申请错误:', error);
    
    if (error.message.includes('申请')) {
      return res.status(400).json({
        success: false,
        message: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '取消申请失败'
    });
  }
});

// 获取申请详情
router.get('/:id', authenticateToken, validateId, async (req, res) => {
  try {
    const applicationId = req.params.id;
    const application = await Application.findById(applicationId);
    
    if (!application) {
      return res.status(404).json({
        success: false,
        message: '申请不存在'
      });
    }
    
    // 检查权限：只有申请者或预约创建者可以查看
    if (application.applicant_id !== req.user.id && 
        application.appointment_creator_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权限查看此申请'
      });
    }
    
    res.json({
      success: true,
      data: application
    });
  } catch (error) {
    console.error('获取申请详情错误:', error);
    res.status(500).json({
      success: false,
      message: '获取申请详情失败'
    });
  }
});

// 获取待处理申请数量
router.get('/pending/count', authenticateToken, async (req, res) => {
  try {
    const count = await Application.getPendingCount(req.user.id);
    
    res.json({
      success: true,
      data: { count }
    });
  } catch (error) {
    console.error('获取待处理申请数量错误:', error);
    res.status(500).json({
      success: false,
      message: '获取待处理申请数量失败'
    });
  }
});

module.exports = router;
